<template>
  <div class="uni-lora-map">
    <el-dialog :fullscreen="true" :close-on-click-modal="false" :visible.sync="visible">
      <span slot="title" class="uni-title">
        历史轨迹（<span class="uni-name">{{user.name}}</span>）
       <!-- <el-popover placement="bottom" width="240" trigger="hover">
          <div class="uni-popover-notice">可以选择日期在<span>30天以内</span>,历史轨迹最长<span>保存30天</span>,超过后自动清除</div>
          <i slot="reference" class="el-icon-question" style="color: #666666;"></i>
        </el-popover> -->
        <span class="uni-map-floor">当前楼层：{{activeFloor.buildingName}}<span class="uni-floor">{{activeFloor.name}}</span></span>
        <span class="uni-floor" v-if="hasPermission('smis:system')" @click="showUwb">显示UWB</span>
      </span>
      <LoraMap ref="currentMap"/>
      <UserPopover :showHistory="false" :textAlign="textAlign" ref="userPopover" />
    <!--  <Compass ref="compass" class="uni-compass" /> -->
      <LoraButtons class="uni-buttons" @onToggleMode="toggleMode" />
      <span slot="footer" style="width: 100%;">
        <LoraSlider class="uni-lora-slider" :trackList="trackList" v-model="trackSlider" />
        <div class="uni-footer-body uni-flex">
          <div class="uni-fun-play uni-flex">
            <span class="uni-time-title">轨迹时间段
              <el-popover placement="top" width="240" trigger="hover">
                <div class="uni-popover-notice">可以选择日期在<span>30天以内</span>,历史轨迹最长<span>保存30天</span>,超过后自动清除</div>
                <i slot="reference" class="el-icon-question" style="color: #666666;"></i>
              </el-popover>
            </span>
            <el-date-picker style="width: 380px; margin-right: 20px;" v-model="timeRange" type="datetimerange"
              align="center" size="small" unlink-panels range-separator="至" start-placeholder="开始时间"
              end-placeholder="结束时间" @change="pickerChange" :picker-options="pickerOptions">
            </el-date-picker>
            <el-button type="primary" :icon="playIcon" :loading="playState===1" round
              @click="playState === -1 ? queryHistory() : playTrack()">{{playText}}</el-button>
            <div class="uni-speed uni-flex">
              <span>播放速度</span>
              <el-slider class="uni-speed-slider" :min="1" :max="10" label="播放速度" v-model="trackSpeed"></el-slider>
            </div>
          </div>
        </div>
      </span>
    </el-dialog>
  </div>
</template>
<script>
  import moment from 'moment'
  import LoraMap from '@/components/jfMap/loraMap.vue'
  import UserPopover from '../home/UserPopover'
  // import Compass from '../../../../components/jfMap/compass.vue'
  import LoraButtons from '../home/LoraButtons.vue'
  import LoraSlider from '../home/LoraSlider.vue'
  import * as XcUtil from '../../../../utils/xcutil.js'
  import * as JFMAP from '../../../../components/jfMap/hmap.manage.js'
  let trackTimer = null
  let transPoint = [] // 中间过度点
  let tailList = [] // 记录尾巴
  let lastPoint = null

  export default {
    data() {
      return {
        user: {},
        textAlign: 'left',
        visible: false,
        trackSlider: 0,
        trackSpeed: 5,
        playState: -1, // -1 查询 0 播放  1 加载中  2 暂停
        timeRange: [new Date(2022, 1, 1, 0, 0), new Date(2099, 0, 26, 23, 59)],
        pickerOptions: {
          disabledDate(time) {
            var now = new Date();
            // now.setTime(now.getTime() - 3600 * 1000 * 24 * 30);
            return time.getTime() > now.getTime()+86400000;
          },
          shortcuts: [{
            text: '今天',
            onClick(picker) {
              const now = new Date();
              const start = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 0, 0, 0, 0);
              const end = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 23, 59, 59, 0);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '昨天',
            onClick(picker) {
              const now = new Date();
              now.setTime(now.getTime() - 3600 * 1000 * 24);
              const start = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 0, 0, 0, 0);
              const end = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 23, 59, 59, 0);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近一周',
            onClick(picker) {
              const now = new Date();
              now.setTime(now.getTime() - 3600 * 1000 * 24 * 7);
              const start = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 0, 0, 0, 0);
              const end = new Date();
              picker.$emit('pick', [start, end]);
            }
          }]
        },
        activeFloorId: '',
        trackList: []
      }
    },
    components: {
      LoraMap,
      UserPopover,
      // Compass,
      LoraButtons,
      LoraSlider
    },
    mounted() {
      var trackSpeed = localStorage.getItem('trackSpeed'+this.projectId)
      if (trackSpeed && trackSpeed !== '') {
        this.trackSpeed = parseInt(trackSpeed)
      }
    },
    watch: {
      trackSlider(val) {
        if (val < this.trackList.length) {
          if (this.$refs.userPopover) {
            var track = this.trackList[val]
            this.$refs.userPopover.setList([{
              label: this.user.name,
              value: moment(track.createDate).format("HH:mm:ss")
            }])
          }
        }
      },
      trackSpeed(val) {
        localStorage.setItem('trackSpeed'+this.projectId, val)
      },
      visible(val) {
        if (!val) {
          if (trackTimer) {
            clearTimeout(trackTimer)
            trackTimer = null
          }
          this.activeFloorId = ''
          this.playState = -1
          this.trackSlider = 0
          transPoint = [] // 中间过度点
          tailList = [] // 记录尾巴
        }
        if(this.$refs.currentMap) {
          this.$refs.currentMap.getMapManager().setMapWork(val)
        }
      }
    },
    beforeDestroy() {
      if (trackTimer) {
        clearTimeout(trackTimer)
        trackTimer = null
      }
    },
    methods: {
      init(row) {
        // console.log(row)
        this.user = row;
        if (trackTimer) {
          clearTimeout(trackTimer)
          trackTimer = null
        }
        this.activeFloorId = ''
        this.playState = -1
        transPoint = [] // 中间过度点
        tailList = [] // 记录尾巴
        this.visible = true
        lastPoint = null
        const now = new Date();
        const start = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 0, 0, 0, 0);
        const end = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 23, 59, 59, 0);
        this.timeRange = [start, end]

        this.$nextTick(()=>{
          this.$refs.currentMap.reset();
          this.queryHistory()
        })
      },
      pickerChange() {
        this.playState = -1
      },
      showUser(point) {
        if (!point) {
          return
        }
        if (!this.$refs.currentMap) {
          return
        }
        if(this.activeFloorId !== point.floorId) {
          this.$refs.currentMap.showFloors([point.floorId], []);
          this.activeFloorId = point.floorId
          tailList = [];
        }
        this._showUser(point)
      },
      showUwb() {
        this.$refs.currentMap.showUwb();
      },
      playTrack() {
        if (this.playState === 0) {
          this.playState = 2
        } else if (this.playState === 2) {
          this.playState = 0
        }
        if (this.playState === 2) {
          // 开始播放
          this.textAlign = 'center'
          tailList = []
          lastPoint = null
          trackTimer = setTimeout(this._moveTrack, 1000 / this.trackSpeed)
        } else {
          tailList = []
          if (trackTimer) {
            clearTimeout(trackTimer)
            trackTimer = null
          }
        }
      },
      _moveTrack() {
        if (transPoint.length > 0) {
          this.showUser(transPoint.shift());
          trackTimer = setTimeout(this._moveTrack, 1000 / this.trackSpeed)
          return
        }
        var track = this.trackList[this.trackSlider];
        trackTimer = setTimeout(this._moveTrack, this.activeFloorId == track.floorId ? 1000 / this.trackSpeed : 2000)
        var points = this.getTrackPoints(lastPoint, track); // 从上个位置到track位置经过的点
        lastPoint = track;
        if (points.length > 1) {
          this.showUser(points.shift());
          transPoint = points;
          return
        }
        if (points.length === 1) {
          this.showUser(points[0]);
        }
        this.trackSlider++
        if (this.trackSlider >= this.trackList.length) {
          this.playState = 0
          this.trackSlider = 0
          if (trackTimer) {
            clearTimeout(trackTimer)
            trackTimer = null
          }
        }
      },
      getTrackPoints(start, end) {
      	if(!end) {
      		return [start]
      	}
        if(!start || start.floorId !== end.floorId) {
          return [end]
        }
        var points = []
        var distance =  XcUtil.distance(start, end)*0.1;
        for(var i=0; i<distance; i++) {
          if(i == 0) {
            points.push({
              floorId: start.floorId,
              x: start.x+(end.x-start.x)*i/distance,
              y: start.y+(end.y-start.y)*i/distance,
              z: start.z+(end.z-start.z)*i/distance,
              remarks: start.remarks
            })
          } else {
            points.push({
              floorId: start.floorId,
              x: start.x+(end.x-start.x)*i/distance,
              y: start.y+(end.y-start.y)*i/distance,
              z: start.z+(end.z-start.z)*i/distance
            })
          }
        }
        return points;
      },
      queryHistory() {
        if (this.timeRange === null) {
          this.$message.error('请选择轨迹时间段');
          return
        }
        // playState: 2,   // -1 查询 0 播放  1 加载中  2 暂停
        this.playState = 1
        this.$http({
          url: '/lora/api/queryTrack',
          method: 'get',
          params: {
            'userId': this.user.id,
            beginCreateDate: moment(this.timeRange[0]).format("YYYY-MM-DD HH:mm:ss"),
            endCreateDate: moment(this.timeRange[1]).format("YYYY-MM-DD HH:mm:ss")
          }
        }).then(({
          data
        }) => {
          if (data.success && data.list) {
            this.trackList = data.list || []
            if (this.trackList.length === 0) {
              this.$message.warning('此时间段内未查询到数据');
              this.playState = -1
            } else {
              this.$message.success('数据加载完成');
              this.playState = 0
              this.playTrack()
            }
            this.trackSlider = 0
          } else {
            this.playState = -1
          }
        })
      },
      toggleMode(mode, callback) {
        if (this.$refs.currentMap) {
          this.$refs.currentMap.setViewMode(mode, callback)
        }
      },
      _showUser(point) {
        if (!point) {
          return
        }
        tailList.push(point)
        if (tailList.length > 40) {
          tailList.shift()
        }
        // 绘制小尾巴
        this.$refs.currentMap.drawTrack(tailList)
        this.$refs.currentMap.showUser(this.user.id, this.user, point)
        if( this.$refs.currentMap.hasUser(this.user.id) ) {
          this.$refs.currentMap.getMapManager().coordById(this.user.id, (visible, coord)=>{
            if(visible) {
              this.$refs.userPopover.setPosition(coord.x, coord.y)
            } else {
              this.$refs.userPopover.setPosition(-200, -100)
            }
          });
        }
      }
    },
    computed: {
      playIcon: {
        get() {
          if (this.playState === -1) {
            return 'el-icon-search'
          } else if (this.playState === 0) {
            return 'el-icon-video-play'
          } else if (this.playState === 1) {
            return 'el-icon-loading'
          } else {
            return 'el-icon-video-pause'
          }
        }
      },
      playText: {
        get() {
          if (this.playState === -1) {
            return '查询'
          } else if (this.playState === 0) {
            return '播放'
          } else if (this.playState === 1) {
            return '查询中'
          } else {
            return '暂停'
          }
        }
      },
      activeFloor() {
        for(var i=0; i<this.floorList.length; i++) {
          if(this.floorList[i].id == this.activeFloorId) {
            return this.floorList[i]
          }
        }
        return {
          name: '',
          buildingName: ''
        }
      },
      floorList() {
        return this.$store.state.shopdata.floorList
      },
      buildingList() {
        return this.$store.state.shopdata.buildingList
      },
      projectId() {
        return this.$store.state.config.projectId
      },
      backParam() {
        return this.$store.state.config.backParam
      }
    }
  }
</script>
<style lang="less">
  .uni-lora-map {
    .el-dialog__body {
      height: 100%;
      position: relative;
      padding: 0;
      overflow: hidden;
    }

    .el-dialog__footer {
      padding: 0;
      border-top: none;
      border-radius: 0;
    }
  }
</style>
<style lang="less" scoped="scoped">
  .uni-compass {
    position: absolute;
    top: 30px;
    left: 30px;
    z-index: 10;
  }

  .uni-buttons {
    position: absolute;
    bottom: 30px;
    right: 30px;
    z-index: 10;
  }

  .uni-title {
    font-size: 14px;
  }

  .uni-name {
    font-weight: bold;
    margin: 0px 5px;
    color: #3f8ef7;
  }

  .uni-popover-notice {
    font-size: 12px;

    span {
      color: #F5222D;
    }
  }

  .uni-map-floor {
    margin-left: 30px;
    color: #657180;
    font-size: 14px;

    .uni-floor {
      background-color: #3f8ef7;
      color: #FFFFFF;
      padding: 7px 10px;
      border-radius: 5px;
      font-size: 12px;
      margin-left: 10px;
    }
  }

  .uni-lora-slider {
    width: 100%;
  }

  .uni-footer-body {
    background-color: #f1f1f1;
    height: 100px;
    align-items: center;
    justify-content: center;
    padding-top: 20px;
  }

  .uni-fun-play {
    align-items: center;
    flex-direction: row;

    .uni-time-title {
      font-size: 14px;
      width: 90px;
      color: #657180;
      font-weight: bold;
      text-align: left;
      margin-right: 20px;
    }

    .uni-speed {
      margin-left: 50px;
      align-items: center;

      span {
        font-size: 14px;
        width: 66px;
        color: #657180;
        font-weight: bold;
        text-align: left;
      }

      .uni-speed-slider {
        width: 100px;
      }
    }
  }
</style>
